package com.app.service.impl;

import com.alibaba.excel.EasyExcel;
import com.app.controller.importExcel.ImportExcelListener;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.ElectronicService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TestFileUtil;
import com.app.vo.NameAndValueVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
@Primary
public class ElectronicServiceImpl implements ElectronicService {
    @Autowired
    private ElectronicMapper electronicMapper;

    @Autowired
    private CategoryPhoneMapper categoryPhoneMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private PersonMapper personMapper;


    @Override
    public ElectronicModel getElcById(int id) {
        QueryWrapper<ElectronicModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().eq("id", id);
        ElectronicModel role = electronicMapper.selectOne(queryWrapper);
        if (role == null) {
            return null;
        } else {
            return role;
        }
    }

    @Override
    public Page<ElectronicModel> getPageElcList(int page, int limit, String name, List<Integer> idList, Integer sortType) {
        QueryWrapper<ElectronicModel> queryWrapper = new QueryWrapper<>();
        if (idList == null || idList.size() == 0) {
            queryWrapper.select();
        } else {
            queryWrapper.select().in("person_id", idList);
        }
        if (name != null) {
            queryWrapper.select().like("name", name);
        }
        if (sortType==null || sortType==1){
            queryWrapper.orderByAsc("number").orderByDesc("create_time");
        }else {
            queryWrapper.orderByDesc("number").orderByDesc("create_time");
        }
        Page<ElectronicModel> pages = new Page<>();
        pages.setCurrent(page);
        pages.setSize(limit);
        Page<ElectronicModel> roleList = electronicMapper.selectPage(pages, queryWrapper);
        return roleList;
    }

    @Override
    public List<ElectronicModel> selectListByPersonId(Integer personId, Integer deviceType) {
        QueryWrapper<ElectronicModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().eq("person_id", personId).eq("device_type", deviceType);
        List<ElectronicModel> electronicList = electronicMapper.selectList(queryWrapper);
        return electronicList;
    }


    @Override
    public void update(ElectronicModel model) {
        electronicMapper.updateById(model);
    }

    @Override
    public void insert(ElectronicModel model) {
        electronicMapper.insert(model);
    }

    @Override
    public void delete(int id) {
        electronicMapper.deleteById(id);
    }

    @Override
    public List<ElectronicModel> getStatisticsByIds(List<Integer> idList, String key) {
        QueryWrapper<ElectronicModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(key, "COUNT(*) as count");
        if (idList == null && idList.size() <= 0) {
            queryWrapper.select();
        } else {
            for (int i = 0; i < idList.size(); i++) {
                queryWrapper.or().eq("department_id", idList.get(i));
            }
        }
        queryWrapper.groupBy(key);
        List<ElectronicModel> personModelList = electronicMapper.selectList(queryWrapper);
        return personModelList;
    }

    //    导入设备列表信息
    @Override
    public String importElectronic(MultipartFile file) throws IOException {
        List<String> errorList = new ArrayList<>();
        String path = TestFileUtil.getPath() + "excel.xlsx";
        File localFile = new File(path);
        file.transferTo(localFile);
        String filePath = localFile.getAbsolutePath();
        AtomicReference<Integer> row = new AtomicReference<>(new Integer(0));
        try {
            EasyExcel.read(filePath, ElectronicModel.class, new ImportExcelListener<ElectronicModel>(dateList -> {
                for (ElectronicModel electronicModel : dateList) {
                    //查品牌名称对应ID
                    LambdaQueryWrapper<CategoryPhoneModel> brandId = new LambdaQueryWrapper<>();
                    brandId.eq(CategoryPhoneModel::getName, electronicModel.getBrandText());
                    CategoryPhoneModel categoryPhoneBrand = categoryPhoneMapper.selectOne(brandId);
                    if (categoryPhoneBrand != null) {
                        electronicModel.setBrand(categoryPhoneBrand.getId());
                    }
                    //查型号名称对应ID
                    LambdaQueryWrapper<CategoryPhoneModel> deviceId = new LambdaQueryWrapper<>();
                    deviceId.eq(CategoryPhoneModel::getName, electronicModel.getDeviceText());
                    CategoryPhoneModel categoryPhoneDevice = categoryPhoneMapper.selectOne(deviceId);
                    if (categoryPhoneDevice != null) {
                        electronicModel.setDevice(categoryPhoneDevice.getId());
                    }
                    //查所属人对应ID
                    LambdaQueryWrapper<PersonModel> personId = new LambdaQueryWrapper<>();
                    personId.eq(PersonModel::getIdcard, electronicModel.getIdCard());
                    PersonModel personModel = personMapper.selectOne(personId);
                    if (personModel != null) {
                        electronicModel.setPersonId(personModel.getId());
                    }
                    //查设备类型对应id
                    LambdaQueryWrapper<CategoryModel> deviceType = new LambdaQueryWrapper<>();
                    deviceType.eq(CategoryModel::getName, electronicModel.getDeviceTypeText());
                    CategoryModel categoryDeviceType = categoryMapper.selectOne(deviceType);
                    if (categoryDeviceType != null) {
                        electronicModel.setDeviceType(categoryDeviceType.getId());
                    }
                    electronicModel.setCreateTime(CommonHelp.getNowTimestamp());
                    electronicMapper.insert(electronicModel);
                    row.set(row.get() + 1);
                }
                localFile.delete();
            }, errorList)).sheet().headRowNumber(2).doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return "Excel导入失败";
        }
        if (row.get() == 0) {
            return "导入0条，请检查模版或者数据格式";
        }
        StringBuilder msg = new StringBuilder("成功导入" + row + "行。");
        if (errorList.size() != 0) {
            for (String error : errorList) {
                msg.append(error);
            }
        }
        return msg.toString();
    }
//批量删除设备
    @Override
    public Result<Object> deleteElectronicBatchByIds(String ids) {
        // 参数校验
        if (StringUtils.isEmpty(ids)) {
            return Result.success("参数为空，无需删除");
        }
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        // 批量删除
        if (!ListUtils.isEmpty(idsList)) {
            electronicMapper.deleteBatchIds(idsList);
            return Result.success("批量删除成功");
        } else {
            return Result.success("批量删除失败，数据为空");
        }
    }

    /**
     * 个人电子信息设备饼状图
     * @return
     */
    @Override
    public List<NameAndValueVo> electronicPieCount() {
        List<NameAndValueVo> voList =new ArrayList<>();
        int count= 0;
        List<NameAndValueVo> voList1 = electronicMapper.electronicPieCount();
        if (ListUtils.isEmpty(voList1)){
            return voList1;
        }
        for (NameAndValueVo vo :  voList1) {
            if ("设备类型未知".equals(vo.getName())){
                count+=vo.getValue();
            }else {
                voList.add(vo);
            }
        }
        if (count!=0){
            NameAndValueVo vo0 = new NameAndValueVo();
            vo0.setName("设备类型未知");
            vo0.setValue(count);
            voList.add(vo0);
        }
        return voList;
    }
}
